package org.jeecg.modules.demo.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.mes.entity.*;
import org.jeecg.modules.demo.mes.service.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Class:MyPlan
 * @Description:@TODO
 * @Author: author
 * @Date: 2023/1/11 11:45
 */

@Api(tags = "生产计划相关接口")
@RestController
@RequestMapping("/mes/myplan")
@Slf4j
public class PlanController {
    @Autowired
    private ICamelliaMesProcessPlanService camelliaMesProcessPlanService;

    @Autowired
    private ICamelliaMesOrderService orderService;

    @Autowired
    private ICamelliaMesProductService productService;

    @Autowired
    private ICamelliaMesProcessCraftService craftService;

    @Autowired
    private ICamelliaMesByproductService byproductService;


    @Autowired
    private ICamelliaMesMaterialRuleService materialRuleService;

    @Autowired
    private ICamelliaMesSolventRuleService solventRuleService;

    @Autowired
    private ICamelliaMesRawService rawService;

    @Autowired
    private ICamelliaMesSolventService solventService;


    @Autowired
    private IMesOrderRongjiRelService rongjiRelService;

    @Autowired
    private IMesOrderRawRelService rawRelService;


    @Autowired
    private ICamelliaMesProcessPlanService planService;


    @Autowired
    private ICamelliaMesProductRecordService productRecordService;

    @Autowired
    private ICamelliaMesEmpployeeService empployeeService;

    class staff_time {
        String staff_id;
        Date start;
        Date end;
    }


    class office_time {
        String staff_id;
        Date start;
        Date end;
    }


    class machine_time {
        String machine_id;
        Date start;
        Date end;
    }

    @Data
    class timeCombine {
        Date start;
        Date end;
    }

    @AutoLog(value = "退回排单")
    @ApiOperation(value = "退回排单", notes = "退回排单")
    @PostMapping(value = "/back")
    public Result<String> back(@RequestBody CamelliaMesProcessPlan camelliaMesProcessPlan) {
        if (camelliaMesProcessPlan.getProcessStatus() == -2) {
            return Result.error("该订单已经退回了");
        }

        CamelliaMesProcessPlan plan = camelliaMesProcessPlanService.getById(camelliaMesProcessPlan.getId());
        plan.setProcessStatus(-2);
        plan.setAuditComment(camelliaMesProcessPlan.getAuditComment());
        camelliaMesProcessPlanService.updateById(plan);


        //回退溶剂量和物料量
        // 找到对应的订单
        String orderId = camelliaMesProcessPlan.getOrderId();
        CamelliaMesOrder order = orderService.getById(orderId);
        order.setOrderStatus(-2);
        orderService.updateById(order);


        //回退物料
        QueryWrapper<MesOrderRawRel> mesOrderRawRelQueryWrapper = new QueryWrapper<>();
        mesOrderRawRelQueryWrapper.eq("order_id", orderId);
        for (MesOrderRawRel mesOrderRawRel : rawRelService.list(mesOrderRawRelQueryWrapper)) {
            String rawId = mesOrderRawRel.getRawId();
            CamelliaMesRaw raw = rawService.getById(rawId);
            if (raw != null) {
                raw.setStock(raw.getStock() + Double.valueOf(mesOrderRawRel.getNum()));
                rawService.updateById(raw);
            }
            rawRelService.removeById(mesOrderRawRel.getId());
        }

        //回退溶剂量
        QueryWrapper<MesOrderRongjiRel> rongjiRelQueryWrapper = new QueryWrapper<>();
        rongjiRelQueryWrapper.eq("order_id", orderId);
        for (MesOrderRongjiRel mesOrderRongjiRel : rongjiRelService.list(rongjiRelQueryWrapper)) {
            String rongjiId = mesOrderRongjiRel.getRongjiId();
            CamelliaMesSolvent rongji = solventService.getById(rongjiId);
            if (rongji != null) {
                rongji.setStock(rongji.getStock() + Double.valueOf(mesOrderRongjiRel.getNum()));
                solventService.updateById(rongji);
            }
            rongjiRelService.removeById(mesOrderRongjiRel.getId());
        }


        return Result.OK("退回成功！");
    }


    @AutoLog(value = "开始生产")
    @ApiOperation(value = "开始生产", notes = "开始生产")
    @PostMapping(value = "/start_produce")
    public Result<String> start_produce(@RequestBody CamelliaMesProcessPlan camelliaMesProcessPlan) {
        Date date = new Date();
        camelliaMesProcessPlan.setRealStartTime(date);
        camelliaMesProcessPlan.setProcessStatus(2);
        camelliaMesProcessPlanService.updateById(camelliaMesProcessPlan);
        String orderId = camelliaMesProcessPlan.getOrderId();
        CamelliaMesOrder order = orderService.getById(orderId);
        order.setOrderStatus(2);
        orderService.updateById(order);
        return Result.OK("开始生产");
    }

    @Autowired
    IManageDeviceService manageDeviceService;


    @AutoLog(value = "完成生产")
    @ApiOperation(value = "完成生产", notes = "开始生产")
    @PostMapping(value = "/end_produce")
    public Result<String> end_produce(@RequestBody CamelliaMesProcessPlan camelliaMesProcessPlan) {

        Date date = new Date();
        camelliaMesProcessPlan.setRealEndTime(date);
        camelliaMesProcessPlan.setProcessStatus(3);

        String orderId = camelliaMesProcessPlan.getOrderId();
        CamelliaMesOrder order = orderService.getById(orderId);
        order.setOrderStatus(3);


        //产品数量
        String requiredProduct = order.getRequiredProduct();
        CamelliaMesProduct product = productService.getById(requiredProduct);
        product.setStock(product.getStock() + camelliaMesProcessPlan.getOrderNum());

        //插入一条明细记录
        CamelliaMesProductRecord camelliaMesProductRecord = new CamelliaMesProductRecord();
        camelliaMesProductRecord.setCode(camelliaMesProcessPlan.getCode());
        camelliaMesProductRecord.setName(product.getName());
        camelliaMesProductRecord.setYieldDate(new Date());
        camelliaMesProductRecord.setOrderNum(camelliaMesProcessPlan.getOrderNum());
        String machines = camelliaMesProcessPlan.getMachines();
        int i = 0;
        String result = "";
        for (String s : machines.split(",")) {
            if (i > 0) {
                result += ",";
            }
            ManageDevice byId = manageDeviceService.getById(s);
            result += byId.getDeviceName();
            i++;
        }
        camelliaMesProductRecord.setMachine(result);


        //添加负责人
        String principals = camelliaMesProcessPlan.getPrincipal();
        i = 0;
        result = "";
        for (String s : principals.split(",")) {
            if (i > 0) {
                result += ",";
            }
            CamelliaMesEmpployee byId = empployeeService.getById(s);
            result = result + byId.getName();
            i++;
        }
        camelliaMesProductRecord.setPrincipal(result);

        //添加执行员工
        String executors = camelliaMesProcessPlan.getExecutor();
        i = 0;
        result = "";
        for (String s : executors.split(",")) {
            if (i > 0) {
                result += ",";
            }
            CamelliaMesEmpployee byId = empployeeService.getById(s);
            result = result + byId.getName();
            i++;
        }
        camelliaMesProductRecord.setExecutor(result);


        //副产品数量
        QueryWrapper<CamelliaMesByproduct> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("required_material", requiredProduct);
        List<CamelliaMesByproduct> byproduct = byproductService.list(queryWrapper1);
        if (byproduct.size() <= 0) {
            return Result.error("缺少对应的副产品记录");
        } else {
            CamelliaMesByproduct byproduct1 = byproduct.get(0);
            byproduct1.setProductStock(camelliaMesProcessPlan.getByproductNum() + byproduct1.getProductStock());
            byproductService.updateById(byproduct1);
        }


        camelliaMesProcessPlanService.updateById(camelliaMesProcessPlan);
        productService.updateById(product);
        productRecordService.save(camelliaMesProductRecord);
        orderService.updateById(order);
        return Result.OK("完成生产");
    }


    @AutoLog(value = "生产计划排单")
    @ApiOperation(value = "生产计划排单", notes = "生产计划排单")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_process_plan:add")
    @PostMapping(value = "/manual_plan")
    public Result<String> plan(@RequestBody CamelliaMesProcessPlan camelliaMesProcessPlan) {
        if (camelliaMesProcessPlan.getProcessStatus() == 0) {
            ;
        }

        if (camelliaMesProcessPlan.getId() == null) {
            return Result.error("传入id有误");
        }

        if (camelliaMesProcessPlan.getMachines() == null) {
            return Result.error("没有输入机器");
        }

        if (camelliaMesProcessPlan.getPrincipal() == null) {
            return Result.error("没有输入负责人");
        }

        if (camelliaMesProcessPlan.getExecutor() == null) {
            return Result.error("没有输入执行员工");
        }


        Integer processStatus = camelliaMesProcessPlan.getProcessStatus();
        if (processStatus == 0 || processStatus == -2 || processStatus == -3) {
            ;
        } else {
            return Result.error("订单状态错误，无法排单");
        }

        CamelliaMesRaw pre_raw = new CamelliaMesRaw();
        MesOrderRawRel pre_raw_rel = new MesOrderRawRel();
        CamelliaMesSolvent pre_rongji = new CamelliaMesSolvent();
        MesOrderRongjiRel pre_rongji_rel = new MesOrderRongjiRel();
        CamelliaMesOrder order = new CamelliaMesOrder();
        if (camelliaMesProcessPlan.getProcessStatus() != 0) {
            QueryWrapper<CamelliaMesProcessPlan> queryWrapper = new QueryWrapper<>();
            //1.查询对应的产品
            String orderId = camelliaMesProcessPlan.getOrderId();
            order = orderService.getById(orderId);
            order.setOrderStatus(1);
            String requiredProduct = order.getRequiredProduct();
            CamelliaMesProduct product = productService.getById(requiredProduct);
            String requiredCraft = product.getRequiredCraft();
            String[] split = requiredCraft.split(",");
            String craftid;
            if (requiredCraft.length() > 0) {
                craftid = split[0];
            } else {
                return Result.error("缺少工艺");
            }
            //拿到了工艺
            CamelliaMesProcessCraft craft = craftService.getById(craftid);
            //拿到了规则

            QueryWrapper<CamelliaMesMaterialRule> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("craft_name", craftid);

            List<CamelliaMesMaterialRule> list = materialRuleService.list(queryWrapper1);
            CamelliaMesMaterialRule mesMaterialRule;

            //拿到了规则
            if (list.size() > 0) {
                mesMaterialRule = list.get(0);
            } else {
                return Result.error("缺少原料规则");
            }
            //产品/物料比例
            Double productMaterialRatio = mesMaterialRule.getProductMaterialRatio();

            //订单要求的产品数量
            Double orderNum = order.getOrderNum();

            //原料数量
            Double raw_num = orderNum / productMaterialRatio;

            if (raw_num > 1000000) {
                return Result.error("需求的原料超过了100w，请检查原料规则中的比例");
            }

            //溶剂获取
            QueryWrapper<CamelliaMesSolventRule> queryWrapper2 = new QueryWrapper<>();
            queryWrapper1.eq("craft_name", craftid);

            List<CamelliaMesSolventRule> list2 = solventRuleService.list(queryWrapper2);
            CamelliaMesSolventRule solventRule;
            if (list2.size() > 0) {
                solventRule = list2.get(0);
            } else {
                return Result.error("缺少溶剂规则");
            }

            //产品/溶剂比例
            Double productSolventRatio = solventRule.getProductSolventRatio();

            //溶剂数量
            Double solvent_num = orderNum / productMaterialRatio;

            if (solvent_num > 1000000) {
                return Result.error("需求的溶剂超过了100w，请检查溶剂规则中的比例");
            }

            //找到满足规则的物料
            QueryWrapper<CamelliaMesRaw> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.eq()

            //这里先用简单的判断？ //还有其他的需要判断
            if (mesMaterialRule.getMaterialName()!= null) {
                queryWrapper3.like("name", mesMaterialRule.getMaterialName());
            }
            else{
                return Result.error("物料规则中，名称为空");
            }
            if (mesMaterialRule.getSupplier() != null) {
                queryWrapper3.eq("supplier", mesMaterialRule.getSupplier());
            }
            if(mesMaterialRule.getGrade()!=null) {
                queryWrapper3.eq("material_grade", mesMaterialRule.getGrade());
            }
            if(mesMaterialRule.getOriginPlace()!=null) {
                queryWrapper3.eq("origin_place", mesMaterialRule.getOriginPlace());
            }
            if(mesMaterialRule.getWetDown()!=null&&mesMaterialRule.getWetUp()!=null) {
                queryWrapper3.between("moisture_content", mesMaterialRule.getWetDown(), mesMaterialRule.getWetUp());
            }
            camelliaMesProcessPlan.setOrderNum(orderNum);
            List<CamelliaMesRaw> list1 = rawService.list(queryWrapper3);

            if (list1.size() <= 0) {
                return Result.error("缺少符合条件的物料，请检查物料规则与物料的对应");
            }

            boolean is_enough = false;
            camelliaMesProcessPlan.setOrderProduct(product.getName());


            for (CamelliaMesRaw raw : list1) {
                Double stock = raw.getStock();

                //满足要求
                if (stock >= raw_num) {
                    // 减少了库存
                    raw.setStock(stock - raw_num);
                    pre_raw = raw;
                    // 添加到关系表中
                    MesOrderRawRel mesOrderRawRel = new MesOrderRawRel();
                    mesOrderRawRel.setOrderId(orderId);
                    mesOrderRawRel.setRawId(raw.getId());
                    mesOrderRawRel.setNum(String.valueOf(stock));
                    pre_raw_rel = mesOrderRawRel;
                    camelliaMesProcessPlan.setMaterialIds(raw.getId());
                    is_enough = true;
                    break;
                }
            }
            if (is_enough == false) {
                return Result.error("物料库存不足");
            }


            //找到符合规则的溶剂
            QueryWrapper<CamelliaMesSolvent> queryWrapper4 = new QueryWrapper<>();
            if(solventRule.getSolventName()!=null) {
                queryWrapper4.like("name", solventRule.getSolventName());
            }
            else{
                return Result.error("溶剂规则缺少溶剂名，请检查");
            }
            if(solventRule.getSolventBatch()!=null){
                queryWrapper4.eq("batch", solventRule.getSolventBatch());
            }
            if(solventRule.getSolventType()!=null){
                queryWrapper4.eq("type",solventRule.getSolventType());
            }


            List<CamelliaMesSolvent> list4 = solventService.list(queryWrapper4);
            if (list4.size() <= 0) {
                return Result.error("缺少符合条件的溶剂,，请检查溶剂规则与溶剂的对应");
            }

            is_enough = false;
            for (CamelliaMesSolvent rongji : list4) {
                Double stock = rongji.getStock();

                //满足要求
                if (stock >= raw_num) {
                    // 减少了库存
                    rongji.setStock(stock - raw_num);
                    pre_rongji = rongji;
                    // 添加到关系表中
                    MesOrderRongjiRel mesOrderRongjiRel = new MesOrderRongjiRel();
                    mesOrderRongjiRel.setOrderId(orderId);
                    mesOrderRongjiRel.setRongjiId(rongji.getId());
                    mesOrderRongjiRel.setNum(String.valueOf(stock));
                    pre_rongji_rel = mesOrderRongjiRel;
                    is_enough = true;
                    break;
                }
            }
            if (is_enough == false) {
                return Result.error("溶剂库存不足");
            }
        }
        // 保证时间上不会冲突
        QueryWrapper<CamelliaMesProcessPlan> planQueryWrapper = new QueryWrapper<>();
        planQueryWrapper.eq("process_status", 0);
        planQueryWrapper.or();
        planQueryWrapper.eq("process_status", 1);
        planQueryWrapper.or();
        planQueryWrapper.eq("process_status", 2);
        List<CamelliaMesProcessPlan> list3 = planService.list(planQueryWrapper);

        // 判断员工是否正确
//        CamelliaMesProcessPlan plan = camelliaMesProcessPlan;
//        String executor = plan.getExecutor();
//
//        for (String s : executor.split(",")) {
//            CamelliaMesEmpployee byId = empployeeService.getById(s);
//            String position = byId.getPosition();
//            if(position != "员工"){
//                return Result.error("生产员工所选人员并非员工职位");
//            }
//        }
//        CamelliaMesEmpployee byId = empployeeService.getById(executor);
//        if (byId.getPosition()!="主管"){
//            return Result.error("生产员工所选人员并非员工职位");
//        }
//        String principal = plan.getPrincipal();

        // 计算每个员工和机器的最早结束时间。

//        ArrayList<>
        HashMap<String, timeCombine> staffMap = new HashMap<>();
        HashMap<String, timeCombine> machineMap = new HashMap<>();

        for (CamelliaMesProcessPlan thePlan : list3) {
            if (thePlan.getId().equals(camelliaMesProcessPlan.getId())) {
                System.out.println("continue");
                continue;
            }
            Date estStartTime = thePlan.getEstStartTime();
            Date estEndTime = thePlan.getEstEndTime();
            String principal = thePlan.getPrincipal();
            if (principal != null) {
                String[] principal_s = principal.split(",");
                // 判断
                for (String principal_ : principal_s) {
                    if (staffMap.containsKey(principal_)) {       //如果包含了
                        timeCombine get = staffMap.get(principal_);
                        if (estEndTime != null && get.end != null && estEndTime.after(get.end)) {
                            get.setEnd(estEndTime);
                            staffMap.put(principal_, get);
                        }
                    } else {
                        timeCombine timeCombine = new timeCombine();
                        timeCombine.setStart(estStartTime);
                        timeCombine.setEnd(estEndTime);
                        staffMap.put(principal_, timeCombine);
                    }
                }
            }

            String executor = thePlan.getExecutor();
            if (executor != null) {
                String[] executor_s = executor.split(",");

                for (String principal_ : executor_s) {
                    if (staffMap.containsKey(principal_)) {
                        timeCombine get = staffMap.get(principal_);
                        if (estEndTime != null && get.end != null && estEndTime.after(get.end)) {
                            get.setEnd(estEndTime);
                            staffMap.put(principal_, get);
                        }
                    } else {
                        timeCombine timeCombine = new timeCombine();
                        timeCombine.setStart(estStartTime);
                        timeCombine.setEnd(estEndTime);
                        staffMap.put(principal_, timeCombine);
                    }
                }
            }
            String machines = thePlan.getMachines();
            if (machines != null) {
                String[] machines_s = machines.split(",");

                for (String machine : machines_s) {
                    if (machineMap.containsKey(machine)) {
                        timeCombine get = machineMap.get(machine);
                        if (estEndTime != null && get.end != null && estEndTime.after(get.end)) {
                            get.setEnd(estEndTime);
                            machineMap.put(machine, get);
                        }
                    } else {
                        timeCombine timeCombine = new timeCombine();
                        timeCombine.setStart(estStartTime);
                        timeCombine.setEnd(estEndTime);
                        machineMap.put(machine, timeCombine);
                    }
                }
            }
        }

        // 这时，拿到了两个 map 包含了最早和最晚的信息，接着判断是否冲突
        Date estStartTime = camelliaMesProcessPlan.getEstStartTime();
        Date estEndTime = camelliaMesProcessPlan.getEstEndTime();
        String principal = camelliaMesProcessPlan.getPrincipal();
        if (principal == null) {
            return Result.error("没有提供负责人");
        }
        String[] principal_s = principal.split(",");
        String executor = camelliaMesProcessPlan.getExecutor();
        if (executor == null) {
            return Result.error("没有提供执行员工");
        }
        String[] executor_s = executor.split(",");
        String machines = camelliaMesProcessPlan.getMachines();
        if (machines == null) {
            return Result.error("没有提供机器");
        }
        String[] machines_s = machines.split(",");
        for (String principal_ : principal_s) {

            //包含了负责人
            if (staffMap.containsKey(principal_)) {
                timeCombine timeCombine = staffMap.get(principal_);
                Date end = timeCombine.getEnd();    //结束时间
                if (estStartTime != null && end != null && end.after(estStartTime)) {
                    System.out.println(end);
                    System.out.println(estStartTime);
                    return Result.error("负责人时间冲突");
                }
            }

        }
        for (String principal_ : executor_s) {

            //包含了员工
            if (staffMap.containsKey(principal_)) {
                timeCombine timeCombine = staffMap.get(principal_);
                Date end = timeCombine.getEnd();    //结束时间
                if (estStartTime != null && end != null && end.after(estStartTime)) {
                    return Result.error("员工时间冲突");
                }
            }

        }
        for (String machines_ : machines_s) {
            //包含了机器
            if (machineMap.containsKey(machines_)) {
                timeCombine timeCombine = machineMap.get(machines_);
                Date end = timeCombine.getEnd();    //结束时间
                if (estStartTime != null && end != null && end.after(estStartTime)) {
                    return Result.error("机器时间冲突");
                }
            }
        }


        if (camelliaMesProcessPlan.getProcessStatus() != 0) {
            camelliaMesProcessPlan.setProcessStatus(0);
            rawService.updateById(pre_raw);
            rawRelService.save(pre_raw_rel);
            solventService.updateById(pre_rongji);
            rongjiRelService.save(pre_rongji_rel);
            orderService.updateById(order);
            camelliaMesProcessPlanService.updateById(camelliaMesProcessPlan);
            return Result.OK("排单成功！");
        } else {
            camelliaMesProcessPlan.setProcessStatus(1);
            camelliaMesProcessPlanService.updateById(camelliaMesProcessPlan);
            return Result.OK("审核通过！");
        }
    }


    @AutoLog(value = "自动排单")
    @ApiOperation(value = "自动排单", notes = "自动排单")
    //@RequiresPermissions("org.jeecg.modules.demo:camellia_mes_process_plan:add")
    @PostMapping(value = "/auto_plan")
    public Result<String> plan(@RequestParam(name = "id", required = true) String id) {

        //0.一些函数的可调的默认参数
        int plan_machine_num = 1; //默认排单机器数
        int plan_staff_num = 2; //默认排单执行员工数
        int plan_principal_num = 1; //默认负责人数
        String plan_staff_pos = "员工"; //默认按执行员工按【员工】职位排单
        String plan_principal_pos = "主管"; //默认负责人按【主管】职位排单
        double max_overflow = 1000000; //计算物料/溶剂上限阈值参数，防止系统溢出
        double min_ratio = 0.0001; //规则最小比例下限，防止系统错误

        //1. id 校验和 plan校验
        if (id == null || id.equals("")) return Result.error("提供的id为空");
        CamelliaMesProcessPlan plan = camelliaMesProcessPlanService.getById(id);
        if (plan == null) {
            return Result.error("提供的id错误");
        }

        //2.状态校验
        Integer processStatus = plan.getProcessStatus();
        if (processStatus == 0 || processStatus == -2 || processStatus == -3) {
            ;
        } else {
            return Result.error("订单状态错误，无法排单");
        }

        //3.创建一些预修改的实体
        CamelliaMesRaw pre_raw = new CamelliaMesRaw();
        MesOrderRawRel pre_raw_rel = new MesOrderRawRel();
        CamelliaMesSolvent pre_rongji = new CamelliaMesSolvent();
        MesOrderRongjiRel pre_rongji_rel = new MesOrderRongjiRel();
        CamelliaMesOrder order = new CamelliaMesOrder();

        //4.根据生产计划id获取订单
        String orderId = plan.getOrderId();
        if (orderId == null || orderId.equals("")) return Result.error("缺少订单信息");
        order = orderService.getById(orderId);
        if (order == null) return Result.error("缺少订单信息");
        order.setOrderStatus(1);

        //5.根据订单获取产品信息
        String requiredProduct = order.getRequiredProduct();
        if (requiredProduct == null || requiredProduct.equals("")) return Result.error("缺少产品信息");
        CamelliaMesProduct product = productService.getById(requiredProduct);
        if (product == null) return Result.error("缺少订单信息");

        //6.从产品中获取需要的工艺
        String requiredCraft = product.getRequiredCraft();
        if (requiredCraft == null || requiredCraft.equals("")) return Result.error("缺少工艺信息");
        String[] split = requiredCraft.split(",");
        String craftid;
        if (requiredCraft.length() > 0) {
            craftid = split[0];
        } else {
            return Result.error("缺少工艺");
        }
        //成功获取工艺
        CamelliaMesProcessCraft craft = craftService.getById(craftid);

        //7.获取规则
        QueryWrapper<CamelliaMesMaterialRule> materialRuleQueryWrapper = new QueryWrapper<>();
        materialRuleQueryWrapper.eq("craft_name", craftid);
        List<CamelliaMesMaterialRule> list = materialRuleService.list(materialRuleQueryWrapper);
        CamelliaMesMaterialRule mesMaterialRule;
        //判断规则是否存在
        if (list.size() > 0) {
            mesMaterialRule = list.get(0);
        } else {
            return Result.error("缺少原料规则");
        }

        //8.根据物料规则计算需要的产品数量
        //产品-物料比例
        Double productMaterialRatio = mesMaterialRule.getProductMaterialRatio();
        if (productMaterialRatio < min_ratio) return Result.error("规则中产品物料比小于" + min_ratio + ",请检查规则");
        //订单要求的产品数量
        Double orderNum = order.getOrderNum();
        //原料数量
        Double raw_num = orderNum / productMaterialRatio;

        //简单的规则判断，防止计算出来的数字过大系统溢出
        if (raw_num > max_overflow) {
            return Result.error("需求的原料超过了+" + max_overflow + "，请检查原料规则中的比例");
        }

        //9.查询满足规则的物料
        QueryWrapper<CamelliaMesRaw> rawQueryWrapper = new QueryWrapper<>();
        String materialName = mesMaterialRule.getMaterialName();
        if (materialName == null || materialName.equals("")) return Result.error("缺少原料信息");
        //规则条件（这里先预留）
        rawQueryWrapper.like("name", materialName);
        plan.setOrderNum(orderNum);
        List<CamelliaMesRaw> rawList = rawService.list(rawQueryWrapper);

//        //如果缺少符合条件的规则
//        if (rawList.size() <= 0) {
//            return Result.error("缺少符合条件的物料");
//        }

        //判断符合规则的物料是否有一种是充足的
        boolean is_enough = false;
        plan.setOrderProduct(product.getName());

        //10.遍历并查找物料库存数量，如果找到了库存就预扣减
        for (CamelliaMesRaw raw : rawList) {
            Double stock = raw.getStock();
            //满足要求
            if (stock >= raw_num) {
                // 减少了库存
                raw.setStock(stock - raw_num);
                pre_raw = raw;
                // 添加到关系表中
                MesOrderRawRel mesOrderRawRel = new MesOrderRawRel();
                mesOrderRawRel.setOrderId(orderId);
                mesOrderRawRel.setRawId(raw.getId());
                mesOrderRawRel.setNum(String.valueOf(stock));
                pre_raw_rel = mesOrderRawRel;
                plan.setMaterialIds(raw.getId());
                is_enough = true;
                break;
            }
        }
        if (is_enough == false) {
            return Result.error("物料库存不足");
        }


        //溶剂相关判断
        //11.根据工艺获取到溶剂规则
        QueryWrapper<CamelliaMesSolventRule> solventRuleQueryWrapper = new QueryWrapper<>();
        //溶剂判断条件（预留）
        solventRuleQueryWrapper.eq("craft_name", craftid);

        List<CamelliaMesSolventRule> solventRules = solventRuleService.list(solventRuleQueryWrapper);
        CamelliaMesSolventRule solventRule;
        //查询是否存在对应的溶剂规则
        if (solventRules.size() > 0) {
            solventRule = solventRules.get(0);
        } else {
            return Result.error("缺少溶剂规则");
        }

        //产品-溶剂比例
        Double productSolventRatio = solventRule.getProductSolventRatio();
        if (productSolventRatio < min_ratio) return Result.error("规则中产品物料比小于" + min_ratio + ",请检查规则");

        //溶剂数量
        Double solvent_num = orderNum / productMaterialRatio;
        if (solvent_num > max_overflow) {
            return Result.error("需求的溶剂超过了" + solventRules + "，请检查溶剂规则中的比例");
        }

        //12.找到符合规则的溶剂
        QueryWrapper<CamelliaMesSolvent> solventQueryWrapper = new QueryWrapper<>();
        solventQueryWrapper.like("name", solventRule.getSolventName());
        List<CamelliaMesSolvent> solvents = solventService.list(solventQueryWrapper);
        if (solvents.size() <= 0) {
            return Result.error("缺少符合条件的溶剂");
        }

        //13.遍历并查找溶剂库存数量，如果找到了库存就预扣减
        is_enough = false;
        for (CamelliaMesSolvent solvent : solvents) {
            Double stock = solvent.getStock();
            //满足要求
            if (stock >= raw_num) {
                // 减少了库存
                solvent.setStock(stock - raw_num);
                pre_rongji = solvent;
                // 添加到关系表中
                MesOrderRongjiRel mesOrderRongjiRel = new MesOrderRongjiRel();
                mesOrderRongjiRel.setOrderId(orderId);
                mesOrderRongjiRel.setRongjiId(solvent.getId());
                mesOrderRongjiRel.setNum(String.valueOf(stock));
                pre_rongji_rel = mesOrderRongjiRel;
                is_enough = true;
                break;
            }
        }
        if (is_enough == false) {
            return Result.error("溶剂库存不足");
        }

        // 计算预计工时

        //

        //一键排单成功
        plan.setProcessStatus(0);
        rawService.updateById(pre_raw);
        rawRelService.save(pre_raw_rel);
        solventService.updateById(pre_rongji);
        rongjiRelService.save(pre_rongji_rel);
        orderService.updateById(order);
        camelliaMesProcessPlanService.updateById(plan);
        return Result.OK("一键排单成功！");
    }


}
